package site.teamo.biu.flink.web.controller;

import cn.hutool.core.io.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.teamo.biu.flink.web.configuration.user.UserConfiguration;
import site.teamo.biu.flink.web.controller.model.BiuJSONResult;
import site.teamo.biu.flink.web.controller.model.functionpackage.UploadFunctionPackageResponse;
import site.teamo.biu.flink.web.entity.OperatorPackageDO;
import site.teamo.biu.flink.web.exception.BiuResponseCode;
import site.teamo.biu.flink.web.service.OperatorPackageService;
import site.teamo.biu.flink.web.service.model.functionpackage.VerifyFunctionPackageResult;
import site.teamo.biu.flink.web.util.BiuJSONResultUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author haocongshun
 * @date 2023/10/31 9:30:53
 */
@Api(tags = "算子包操作")
@RestController
@RequestMapping("/api/operator-package")
public class OperatorPackageController {

    @Resource(name = "operatorPackageServiceImpl")
    private OperatorPackageService operatorPackageService;


    @GetMapping("/query-list")
    public BiuJSONResult query(@RequestParam(value = "keyword", required = false) String keyword) {
        return BiuJSONResultUtils.ok(operatorPackageService.queryList(keyword));
    }

    @GetMapping("/info")
    public BiuJSONResult info(@RequestParam(value = "id") String id) {
        return BiuJSONResultUtils.ok(operatorPackageService.info(id));
    }

    @ApiOperation(value = "上传算子包")
    @PostMapping(value = "/upload")
    public BiuJSONResult upload(
            @RequestAttribute(UserConfiguration.USERNAME_ATTRIBUTE_NAME) String username,
            @ApiParam(value = "算子包", required = true) @RequestPart MultipartFile file) {
        if (file.isEmpty()) {
            throw BiuResponseCode.PARAMETER_ERROR.runtimeException("请选择一个文件!");
        }
        VerifyFunctionPackageResult result = operatorPackageService.verify(file);
        if (result.getMessage().size() > 0) {
            FileUtil.del(result.getPackageFileTempPath());
            return BiuJSONResultUtils.ok(new UploadFunctionPackageResponse()
                    .setMessage(result.getMessage()));
        }
        OperatorPackageDO functionPackageDO = operatorPackageService.save(result.getPackageFileTempPath(), result.getDescriptor());
        return BiuJSONResultUtils.ok(new UploadFunctionPackageResponse()
                .setInfo(functionPackageDO));
    }


    @ApiOperation("删除算子包")
    @PostMapping("/delete")
    public BiuJSONResult delete(@RequestBody List<String> ids) {
        operatorPackageService.delete(ids);
        return BiuJSONResultUtils.ok();
    }
}
